<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view class="cu-modal bottom-modal " :class="modalSku ? 'show' : ''" @tap="hideModalSku" catchtouchmove="touchMove">
		<view class="cu-dialog dialo-sku bg-white " :class="modalSku ? 'animation-slide-bottom' : ''" @tap.stop>
			<view class="cu-card article no-card" style="height: 30%">
				<view class="cu-item">
					<view class="content">
						<image
							:src="goodsSpu.picUrls&&goodsSpu.picUrls.length>0 ? goodsSpu.picUrls[0] ? goodsSpu.picUrls[0] : '/static/public/img/no_pic.png': '/static/public/img/no_pic.png'"
							mode="aspectFill" class="row-img margin-top-xs" v-if="!goodsSku ||!goodsSku.salesPrice">
						</image>
						<image
							:src="goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls&&goodsSpu.picUrls.length>0&&goodsSpu.picUrls[0] ? goodsSpu.picUrls[0] : '/static/public/img/no_pic.png'"
							mode="aspectFill" class="row-img margin-top-xs" v-if="goodsSku&&goodsSku.salesPrice">
						</image>
						<view class="desc">
							<view class="text-price margin-top-xl text-bold text-red text-xl"
								v-show="!goodsSku||!goodsSku.salesPrice">{{goodsSpu.priceDown}}<text
									v-show="goodsSpu.priceDown != goodsSpu.priceUp"
									class="text-red margin-lr-xs">-</text><text
									v-show="goodsSpu.priceDown != goodsSpu.priceUp"
									class="text-red text-bold">{{goodsSpu.priceUp}}</text>
							</view>
							<view class="text-price margin-top-xl text-bold text-red text-lg"
								v-show="goodsSku&&goodsSku.salesPrice">{{goodsSku.salesPrice}}</view>
							<view class="text-gray text-sm" v-show="goodsSku.stock != null">库存{{goodsSku.stock}}件</view>
							<view class="text-black text-sm">选择<view class="display-ib"
									v-for="(item, index) in goodsSpecData" :key="index">
									<view class="display-ib" v-show="!item.checked">{{item.value}}</view>
									<view class="display-ib" v-show="item.checked" v-for="(item2, index2) in item.leaf"
										:key="index2">
										<view class="display-ib" v-show="item.checked == item2.id">{{item2.value}}
										</view>
									</view>
									<view class="display-ib" v-show="goodsSpecData.length != (index+1)">,</view>
								</view>
							</view>
							<view>

							</view>
						</view>
					</view>
				</view>
				<view class="text-xl close-icon">
					<text class="cuIcon-close" @tap="hideModalSku"></text>
				</view>
			</view>
			<scroll-view scroll-y scroll-with-animation style="height:60%">
				<!-- 如果不这样会不刷新数据 -->
				<view v-show="false">{{goodsSpecData}}</view>
				<view class="padding-bottom-xs solid-top" v-for="(item, index) in goodsSpecData" :key="index">
					<view class="cu-bar bg-white" style="min-height: 80rpx">
						<view class="action">
							<text class="text-black">{{item.value}}</text>
						</view>
					</view>
					<view class="grid bg-white margin-lr-sm">
						<button class="cu-btn margin-xs" :class="item.checked == item2.id ? 'line-red' : ''"
							v-for="(item2, index2) in item.leaf" :key="index2"
							@tap="skuClick(item2, index, $event, index2)" :data-index="index" :data-index2="index2"
							:disabled="!!item2.disabled">
							<!-- #ifdef -->
							<!-- 用于小程序页面刷新！！ -->
							<text v-show="false">{{JSON.stringify(item2)}}</text>
							<!-- #endif -->
							{{item2.value}}
						</button>
					</view>
				</view>
				<view class="cu-bar bg-white solid-top">
					<view class="action">
						<text class="text-black">数量</text>
					</view>
					<base-stepper customClass="margin-right" :stNum="cartNum" :min="1" :max="goodsSku.stock"
						@numChange="numChange"></base-stepper>
				</view>
			</scroll-view>
			<view class="cu-bar bg-white tabbar border shop foot" style="height: 10%">
				<view class="btn-group" v-if="modalSkuType == ''">
					<!-- <button class="cu-btn bg-orange round shadow-blur m-sku-bn lg" @tap="toDo" data-type="1"
						:disabled="goodsSku.enable == '0'" type>加入购物车</button> -->
					<button class="cu-btn round shadow-blur m-sku-bn lg" :class="'bg-'+theme.themeColor" @tap="toDo"
						data-type="2" :disabled="goodsSku.stock <= 0 || goodsSku.enable == '0'" type>立即购买</button>
				</view>
				<view class="btn-group" v-if="modalSkuType != ''">
					<button class="cu-btn round shadow-blur lg " :class="'bg-'+theme.themeColor" style="width: 90%"
						@tap="toDo" :disabled="(modalSkuType == '2' && goodsSku.stock <= 0) || goodsSku.enable == '0'"
						type :data-type="modalSkuType">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	const app = getApp();
	import baseStepper from "@/components/base-stepper/index";
	import api from 'utils/api'

	export default {
		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				initFirst: true, //只初始化一次
				choiceAll: false, //是否选择全部
				difference: [], //sku列表
				shopItemInfo: {}, //存放要和选中的值进行匹配的数据
				selectArr: [], //存放被选中的值
				subIndex: [], //是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
				selectshop: {}, //存放最后选中的商品
			};
		},
		onLoad() {

		},
		created() {},
		components: {
			baseStepper
		},
		computed: {

		},
		props: {
			shopInfo: {
				type: Object,
				default: () => {}
			},
			goodsSpu: {
				type: Object,
				default: () => {}
			},
			goodsSpecData: {
				type: Array,
				default: () => []
			},
			goodsSku: {
				type: Object,
				default: () => ''
			},
			modalSku: {
				type: Boolean,
				default: false
			},
			modalSkuType: {
				type: String,
				default: ''
			},
			cartNum: {
				type: Number,
				default: 1
			},
			shoppingCartId: {
				type: String,
				default: null
			}
		},

		watch: {
			goodsSpu(val, oldVal) {},
			goodsSku(val) {},
			goodsSpecData(val, oldVal) { // 这个数据是最后请求的，所以这个有数据表示就能初始化规格数据了，initFirst：监控是否重复初始化数据
				if (val != oldVal && this.initFirst) {
					this.initSpecData();
				}
			},
		},
		methods: {
			initSpecData(goodsSpecData) {
				if (goodsSpecData) {
					if (this.goodsSpecData.length > 0) {
						this.goodsSpecData.splice(0, this.goodsSpecData.length);
					}
					goodsSpecData.map(item => {
						this.goodsSpecData.push(item);
					});
				}
				if (this.goodsSpu && this.goodsSpu.skus) {
					this.initFirst = false;
					// this.difference: [], //sku列表 {"id": "23","price": 500,"stock": 48,"difference": ["100","绿色","X","豪华"]}
					this.shopItemInfo = {}, //存放要和选中的值进行匹配的数据
						this.selectArr = [], //存放被选中的值
						this.subIndex = []; //是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
					//初始化数据
					if (this.goodsSpecData.length > 0) {
						this.goodsSpecData.map(item => {
							item.diabled = false; //是否点击
							item.ishow = true; //是否显示，暂时无用
							this.selectArr.push(item.checked ? item.checked : '');
							this.subIndex.push(-1);
						});
					}
					this.changeData(this.goodsSpu.skus)
					this.checkItem(); //计算sku里面规格形成路径
					this.checkInpath(-1); //传-1是为了不跳过循环
				}
			},
			changeData(differenceList) {
				for (let item of differenceList) {
					let nowOneCompound = []
					for (let oneCompound of item.specs) {
						nowOneCompound.push(oneCompound.specValueId)
					}
					item.difference = nowOneCompound
				}
			},
			checkItem() {
				// console.time('计算有多少种可选路径需要的时间是');
				//计算有多少种可选路径
				let result = this.goodsSpu.skus.reduce(
					(arrs, items) => {
						return arrs.concat(
							items.difference.reduce(
								(arr, item) => {
									return arr.concat(
										arr.map(item2 => {
											//利用对象属性的唯一性实现二维数组去重
											if (!this.shopItemInfo.hasOwnProperty([...item2, item])) {
												this.shopItemInfo[[...item2, item]] = items;
											}
											return [...item2, item];
										})
									);
								},
								[
									[]
								]
							)
						);
					},
					[
						[]
					]
				);
				// console.timeEnd('计算有多少种可选路径需要的时间是');
			},
			arrayPermute(input) {
				var permArr = [],
					usedChars = [];

				function main(input) {
					var i, ch;
					for (i = 0; i < input.length; i++) {
						ch = input.splice(i, 1)[0];
						usedChars.push(ch);
						if (input.length == 0) {
							permArr.push(usedChars.slice());
						}
						main(input);
						input.splice(i, 0, ch);
						usedChars.pop();
					}
					return permArr
				}
				return main(input);
			},
			checkSkuItem(arr) { // 判断是否有该sku
				// this.shopItemInfo.hasOwnProperty(choosed_copy2)
				let selectVal = null
				let resultArr = this.arrayPermute(arr)
				for (var i = 0; i < resultArr.length; i++) {
					if (this.shopItemInfo.hasOwnProperty(resultArr[i])) {
						selectVal = resultArr[i]
						break;
					}
				}
				return selectVal;
			},
			checkInpath(clickIndex) {
				// console.time('筛选可选路径需要的时间是');
				//循环所有属性判断哪些属性可选
				//当前选中的兄弟节点和已选中属性不需要循环
				for (let i = 0, len = this.goodsSpecData.length; i < len; i++) {
					if (i == clickIndex) {
						continue;
					}
					let len2 = this.goodsSpecData[i].leaf.length;
					for (let j = 0; j < len2; j++) {
						if (this.subIndex[i] != -1 && j == this.subIndex[i]) {
							continue;
						}
						let choosed_copy = [...this.selectArr];
						this.$set(choosed_copy, i, this.goodsSpecData[i].leaf[j].id);
						let choosed_copy2 = choosed_copy.filter(item => item !== '' && typeof item !== 'undefined');
						// 判断是否有该sku
						// if (this.shopItemInfo.hasOwnProperty(choosed_copy2)) {
						if (this.checkSkuItem(choosed_copy2)) {
							this.$set(this.goodsSpecData[i].leaf[j], 'ishow', true);
							this.$set(this.goodsSpecData[i].leaf[j], 'disabled', false);
						} else {
							this.$set(this.goodsSpecData[i].leaf[j], 'ishow', false);
							this.$set(this.goodsSpecData[i].leaf[j], 'disabled', true);
						}
					}
				}
				// console.timeEnd('筛选可选路径需要的时间是');
			},
			skuClick(value, index1, event, index2) {
				uni.showLoading()
				this.goodsSpecData[index1].checked = this.goodsSpecData[index1].checked == value.id ? '' : value
					.id; //已选择过的可以取消
				if (value.ishow) {
					if (this.selectArr[index1] != value.id) {
						this.$set(this.selectArr, index1, value.id);
						this.$set(this.subIndex, index1, index2);
					} else {
						this.$set(this.selectArr, index1, '');
						this.$set(this.subIndex, index1, -1);
					}
					this.checkInpath(index1);
					// 如果全部选完
					if (this.selectArr.every(item => item != '')) {
						// this.selectshop = this.shopItemInfo[this.selectArr];
						this.selectshop = this.shopItemInfo[this.checkSkuItem(this.selectArr)];
						if (this.selectshop) { //是否有商品 sku
							if (this.selectshop.stock == 0) {
								this.$emit('numChange', 0);
							} else {
								if (this.cartNum > this.selectshop.stock) { // 如果已选择的数量大于库存数量，那么选择的数量直接使用最大库存数量
									this.$emit('numChange', this.selectshop.stock);
								} else if (this.cartNum == 0) {
									this.$emit('numChange', 1);
								}
							}
							this.$emit('changeGoodsSku', this.selectshop);
						} else {
							this.$emit('numChange', 0);
						}
						this.choiceAll = true;
					} else {
						this.$emit('changeGoodsSku', {});
						this.choiceAll = false;
					}
				} else {
					this.$emit('changeGoodsSku', {});
					this.choiceAll = false;
				}
				this.$emit('changeSpec', this.goodsSpecData);

				uni.hideLoading()
			},


			touchMove() {
				return;
			},
			hideModalSku() {
				this.$emit('changeModalSku', false);
			},
			numChange(val) {
				this.$emit('numChange', val);
			},

			//提交
			toDo(e) {
				let canDo = true;
				try {
					this.goodsSpecData.forEach(function(spec) {
						if (!spec.checked) {
							canDo = false;
							uni.showToast({
								title: '请选择' + spec.value,
								icon: 'none',
								duration: 2000
							});
							throw new Error();
						}
					});
				} catch (e) {}

				if (this.cartNum < 1 && e.currentTarget.dataset.type != '1') { //如果选择的数量小于1,那么就不能进行购买操作
					uni.showToast({
						title: '数量必须大于0',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				if (canDo) {
					let goodsSpu = this.goodsSpu;
					let goodsSku = this.goodsSku;
					let specInfo = '';
					let goodsSpecData = this.goodsSpecData;
					goodsSpecData.forEach(function(spec, index) {
						spec.leaf.forEach(function(specItem) {
							if (spec.checked == specItem.id) {
								specInfo = specInfo + specItem.value;
								if (goodsSpecData.length != index + 1) {
									specInfo = specInfo + ';';
								}
							}
						});
					});

					if (e.currentTarget.dataset.type == '1') {
						//加购物车 ，库存必须大于0
						// if (goodsSku.stock <= 0) {
						// 	uni.showToast({
						// 		title: '库存数量为0',
						// 		icon: 'none',
						// 		duration: 5000
						// 	});
						// 	return
						// }
						if (this.shoppingCartId) {
							api.shoppingCartUpdate({
								id: this.shoppingCartId,
								spuId: goodsSpu.id,
								skuId: goodsSku.id,
								quantity: this.cartNum,
								addPrice: goodsSku.salesPrice,
								spuName: goodsSpu.name,
								specInfo: specInfo,
								picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0]
							}).then(res => {
								uni.showToast({
									title: '修改成功',
									duration: 5000
								});
								this.hideModalSku();
								this.$emit('operateCartEvent');
							});
						} else {
							api.shoppingCartAdd({
								spuId: goodsSpu.id,
								skuId: goodsSku.id,
								quantity: this.cartNum,
								addPrice: goodsSku.salesPrice,
								shopId: goodsSpu.shopId,
								spuName: goodsSpu.name,
								specInfo: specInfo,
								picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0]
							}).then(res => {
								uni.showToast({
									title: '添加成功',
									duration: 5000
								});

								this.hideModalSku();
								this.$emit('operateCartEvent');
							});
						}
					} else {
						//立即购买，前去确认订单
						/* 把参数信息异步存储到缓存当中 */
						console.log(goodsSku,goodsSpu,goodsSpecData,555);
						uni.setStorage({
							key: 'param-orderConfirm',
							data: [{
								spuId: goodsSpu.id,
								skuId: goodsSku.id,
								tenantId:goodsSpu.tenantId,
								shopId:goodsSpu.shopId,
								threePartiesGoodType: goodsSpu.threePartiesGoodType,
								quantity: this.cartNum,
								salesPrice: goodsSku.salesPrice,
								spuName: goodsSpu.name,
								specInfo: specInfo,
								shopInfo: this.shopInfo,
								picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
								pointsDeductSwitch: goodsSpu.pointsDeductSwitch,
								pointsDeductScale: goodsSpu.pointsDeductScale,
								pointsDeductAmount: goodsSpu.pointsDeductAmount,
								pointsGiveSwitch: goodsSpu.pointsGiveSwitch,
								pointsGiveNum: goodsSpu.pointsGiveNum,
								freightTemplat: goodsSpu.freightTemplat,
								weight: goodsSku.weight,
								volume: goodsSku.volume
							}]
						});
						uni.navigateTo({
							url: '/pages/order/order-confirm/index'
						});
					}
					this.initFirst = true;
				}
			}
		}
	};
</script>
<style>
	.m-sku-bn {
		width: 45%
	}

	.row-img {
		width: 240rpx !important;
		height: 240rpx !important;
		border-radius: 10rpx
	}

	.dialo-sku {
		height: 80%;
	}

	.cu-modal {
		text-align: unset
	}

	.close-icon {
		position: absolute;
		right: 20rpx;
		top: 20rpx
	}
</style>